import { defineStore } from 'pinia';

export const useUserInfo = defineStore('userInfo', {
  state: () => ({
    userInfo: {
      id: 0,
      imgs: '',
      account: ''
    },
    url: '',
    menuList: []
  }),
  actions: {
    setUserInfos(data: any) {
      // 安全检查
      if (!data) {
        this.userInfo = { id: 0, imgs: '', account: '' };
        this.url = '';
        this.menuList = [];
        return;
      }
      // 安全获取 list
      const rawList = data.list || data.menuList || data.menus || data.routes || [];
      if (!Array.isArray(rawList)) {
        this.menuList = [];
      } else {
        // 深拷贝并处理
        let listCopy = JSON.parse(JSON.stringify(rawList));
        // 处理路由
        if (listCopy.length > 0) {
          listCopy.forEach((item: any, index: number) => {
            if (item.path === '/') {
              item.path = '/employee';
            }
          });
          // 处理单子节点
          listCopy.forEach((item: any, index: number) => {
            if (item.children && item.children.length === 1) {
              if (item.path === item.children[0]?.path) {
                delete item.children;
              }
            }
          });
        }
        this.menuList = listCopy;
      }
      // 设置用户信息
      this.userInfo = data.info || data.userInfo || data.user || {
        id: data.id || 0,
        imgs: data.imgs || '',
        account: data.account || data.userName || ''
      };
      this.url = data.url || '';
    },
  },
  persist: {
    enabled: true,  // 开启持久化
  }
});